package com.incar.chuxing.activity;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Point;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Build;
import android.os.Handler;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.MotionEvent;
import android.view.View;
import android.view.animation.TranslateAnimation;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.baidu.location.BDAbstractLocationListener;
import com.baidu.location.BDLocation;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.BitmapDescriptorFactory;
import com.baidu.mapapi.map.MapStatus;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.MyLocationConfiguration;
import com.baidu.mapapi.map.MyLocationData;
import com.baidu.mapapi.map.UiSettings;
import com.baidu.mapapi.model.LatLng;
import com.baidu.mapapi.search.core.PoiInfo;
import com.baidu.mapapi.search.core.SearchResult;
import com.baidu.mapapi.search.poi.OnGetPoiSearchResultListener;
import com.baidu.mapapi.search.poi.PoiDetailResult;
import com.baidu.mapapi.search.poi.PoiIndoorResult;
import com.baidu.mapapi.search.poi.PoiNearbySearchOption;
import com.baidu.mapapi.search.poi.PoiResult;
import com.baidu.mapapi.search.poi.PoiSearch;
import com.baidu.mapapi.search.poi.PoiSortType;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.google.gson.Gson;
import com.incar.chuxing.BuildConfig;
import com.incar.chuxing.R;
import com.incar.chuxing.activity.driving.DrivingActivity;
import com.incar.chuxing.activity.driving.SearchParkActivity;
import com.incar.chuxing.adapter.DeliverLocAdapter;
import com.incar.chuxing.api.ApiStore;
import com.incar.chuxing.api.UrlContainer;
import com.incar.chuxing.application.MyApplication;
import com.incar.chuxing.baiduMap.LocationFilter;
import com.incar.chuxing.baiduMap.MapStatusUtils;
import com.incar.chuxing.baiduMap.MarkerOverlay.OverlayUtils;
import com.incar.chuxing.base.BaseActivity;
import com.incar.chuxing.bean.CityBoundBean;
import com.incar.chuxing.bean.CountDownCloseEvent;
import com.incar.chuxing.bean.JudgeOrderBean;
import com.incar.chuxing.bean.PoiInfoBean;
import com.incar.chuxing.bean.PreOrderDetailBean;
import com.incar.chuxing.utils.AppManager;
import com.incar.chuxing.utils.Constants;
import com.incar.chuxing.utils.DensityUtils;
import com.incar.chuxing.utils.Dialogs.DialogTwoButton;
import com.incar.chuxing.utils.ImageLoader;
import com.incar.chuxing.utils.IntentKey;
import com.incar.chuxing.utils.Logger;
import com.incar.chuxing.utils.RxBus;
import com.incar.chuxing.utils.SDCardUtils;
import com.incar.chuxing.utils.SPKey;
import com.incar.chuxing.utils.SPUtils;
import com.incar.chuxing.utils.SystemToastUtils;
import com.incar.chuxing.utils.ToastUtils;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import okhttp3.MediaType;
import okhttp3.RequestBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class DeliverCarMapActivity extends BaseActivity implements OnGetPoiSearchResultListener, SensorEventListener {

    @BindView(R.id.deliver_mapView)
    MapView deliverMapView;
    @BindView(R.id.deliver_picker_location)
    RelativeLayout deliverPickerLocation;
    @BindView(R.id.deliver_bottom)
    RelativeLayout deliverBottom;
    @BindView(R.id.rl_mapview)
    RelativeLayout rlMapview;
    @BindView(R.id.deliver_location_iv)
    ImageView deliverLocationIv;
    @BindView(R.id.deliver_canOrder_tip)
    TextView canOrderTip;
    @BindView(R.id.deliver_loc_search)
    LinearLayout deliverLocSearch;
    @BindView(R.id.deliver_bottom_rv)
    RecyclerView deliverBottomRv;
    @BindView(R.id.deliver_loc_confirm)
    TextView deliverLocConfirm;
    @BindView(R.id.title_back)
    ImageView titleBack;
    @BindView(R.id.deliver_loc_search_et)
    EditText deliverLocSearchEt;
    @BindView(R.id.imageView_locate)
    ImageView imageViewLocate;
    @BindView(R.id.deliver_car_brandModelOrOrderDetail)
    TextView deliverCarBrandModelOrOrderDetail;
    @BindView(R.id.deliver_cancel_order)
    TextView deliverCancelOrder;
    @BindView(R.id.deliver_car_iv)
    ImageView deliverCarIv;
    @BindView(R.id.deliver_car_license)
    TextView deliverCarLicense;
    @BindView(R.id.deliver_line)
    View deliverLine;
    @BindView(R.id.deliver_order_level)
    TextView deliverOrderLevel;
    @BindView(R.id.deliver_rl_level)
    RelativeLayout deliverRlLevel;
    @BindView(R.id.deliver_order_loc)
    TextView deliverOrderLoc;
    @BindView(R.id.deliver_rl_loc)
    RelativeLayout deliverRlLoc;
    @BindView(R.id.deliver_order_time)
    TextView deliverOrderTime;
    @BindView(R.id.deliver_rl_time)
    RelativeLayout deliverRlTime;
    @BindView(R.id.deliver_order_days)
    TextView deliverOrderDays;
    @BindView(R.id.deliver_rl_days)
    RelativeLayout deliverRlDays;
    @BindView(R.id.deliver_bottom_ll)
    RelativeLayout deliverBottomLl;
    private BaiduMap mBaiduMap;
    private PoiSearch mPoiSearch;
    private OverlayUtils overlayUtils;
    private Context mContext = this;
    private SensorManager mSensorManager;
    private Double lastX = 0.0;
    public LatLng curPosition;
    private MyLocationData locData;
    public LocationClient mLocClient;
    private boolean isFirstLocation = true;
    private MapStatusUtils mapStatusUtils;
    private Point centerPoint;
    public static LatLng centerLocation;
    private LatLng useCarLoc;
    private String useCarAddress;
    private boolean canPoiSearch = true;
    private DeliverLocAdapter rcAdapter;
    private List<PoiInfoBean> poiInfoBeans;
    private boolean canAnimation;
    Handler handler = new Handler();
    Runnable runnable = new Runnable() {
        @Override
        public void run() {
            handler.postDelayed(runnable, 60000);
            getPreOrderDetail();
        }
    };
    private String preOrderId;

    @Override
    public int getLayoutId() {
        return R.layout.activity_deliver_car_map;
    }

    @Override
    public void initView() {
        mPoiSearch = PoiSearch.newInstance();
        mPoiSearch.setOnGetPoiSearchResultListener(this);
        mSensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);//获取传感器管理服务
        deliverMapView.showZoomControls(false);
        if (mBaiduMap == null) {
            mBaiduMap = deliverMapView.getMap();
            // 开启定位图层
            mBaiduMap.setBuildingsEnabled(false);
            mBaiduMap.setMyLocationEnabled(true);
            mBaiduMap.setMyLocationConfiguration(new MyLocationConfiguration(
                    MyLocationConfiguration.LocationMode.NORMAL, true,
                    BitmapDescriptorFactory.fromResource(R.drawable.icon_mylocation), 0x00000000, 0x00000000));
            //设置地图交互
            UiSettings uiSettings = mBaiduMap.getUiSettings();
            uiSettings.setRotateGesturesEnabled(false);
            uiSettings.setOverlookingGesturesEnabled(false);
            uiSettings.setZoomGesturesEnabled(true);
            // 定位初始化
            mLocClient = new LocationClient(this);
            LocationClientOption option = new LocationClientOption();
            option.setIsNeedAddress(true);
            option.setIsNeedLocationDescribe(true);
            option.setOpenGps(true); // 打开gps
            option.setCoorType("bd09ll"); // 设置坐标类型
            option.setScanSpan(8000);
            mLocClient.setLocOption(option);
            mLocClient.registerLocationListener(mListener);
            overlayUtils = new OverlayUtils(mContext, mBaiduMap);
            mapStatusUtils = new MapStatusUtils(mContext, mBaiduMap);
            curPosition = new LatLng(Double.parseDouble(((MyApplication) (MyApplication.getInstance())).getCurPosition()[0] + ""), Double.parseDouble(((MyApplication) (MyApplication.getInstance())).getCurPosition()[1] + ""));
            mapStatusUtils.animateMove(curPosition, 17, 300);
            mBaiduMap.setOnMapStatusChangeListener(new BaiduMap.OnMapStatusChangeListener() {
                @Override
                public void onMapStatusChangeStart(MapStatus mapStatus) {
                    Logger.i("deliver", "status-start");
                    if (getIntent().getIntExtra("intentFrom", 0) == 0) {
                        if (canAnimation) {
                            TranslateAnimation translateAnimation = new TranslateAnimation(0, 0, 0, -DensityUtils.dp2px(mContext, 18f));
                            translateAnimation.setDuration(300);
                            translateAnimation.setRepeatCount(100);
                            deliverLocationIv.startAnimation(translateAnimation);
                        }
                    }
                }

                @Override
                public void onMapStatusChangeStart(MapStatus mapStatus, int i) {
                }

                @Override
                public void onMapStatusChange(MapStatus mapStatus) {
                }

                @Override
                public void onMapStatusChangeFinish(MapStatus mapStatus) {
                    Logger.i("deliver", "status_finish");
                    if (getIntent().getIntExtra("intentFrom", 0) == 0) {
                        try {
                            deliverLocationIv.clearAnimation();
                            if (canPoiSearch) {
                                centerLocation = mapStatus.target;
                                if (centerLocation == null) {
                                    centerLocation = curPosition;
                                }
                                Logger.i("deliver", centerLocation.latitude + "centerLocation" + centerLocation.longitude + "");
                                Logger.i("deliver", curPosition.latitude + "curPosition" + curPosition.longitude + "");
                                mPoiSearch.searchNearby(new PoiNearbySearchOption()
                                        .keyword("停车场")
                                        .sortType(PoiSortType.distance_from_near_to_far)
                                        .location(centerLocation)
                                        .radius(5000)
                                        .pageCapacity(5)
                                        .pageNum(0));
                                Logger.i("deliver", "poi_serach_start");
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                }
            });
            mBaiduMap.setOnMapTouchListener(new BaiduMap.OnMapTouchListener() {
                @Override
                public void onTouch(MotionEvent motionEvent) {
                    canPoiSearch = true;
                    canAnimation = true;
                }
            });

            //添加围栏
            String boundCache = SDCardUtils.loadFileFromSDCardToStirng(SDCardUtils.getSDCardPrivateCacheDir(mContext) + File.separator + "boundCache.txt");
            if (!TextUtils.isEmpty(boundCache)) {
                CityBoundBean cityBoundBean = new Gson().fromJson(boundCache, CityBoundBean.class);
                if (overlayUtils != null && cityBoundBean.getAttachment() != null && cityBoundBean.getAttachment().getFenceArea() != null && cityBoundBean.getAttachment().getFenceArea().size() > 0) {
                    overlayUtils.allBounds = cityBoundBean.getAttachment().getFenceArea();
                    overlayUtils.addBoundsDriving();
                }
            }
            //初始化信息
            if (getIntent().getIntExtra("intentFrom", 0) == 0) {
                deliverLocSearch.setVisibility(View.VISIBLE);
                canOrderTip.setVisibility(View.VISIBLE);
                deliverPickerLocation.setVisibility(View.VISIBLE);
                deliverLocConfirm.setVisibility(View.VISIBLE);
                deliverBottomRv.setVisibility(View.VISIBLE);
                deliverBottomLl.setVisibility(View.GONE);
            } else if (getIntent().getIntExtra("intentFrom", 0) == 1) {
                preOrderId = getIntent().getStringExtra("preOrderId");
                handler.post(runnable);
                deliverBottomLl.setVisibility(View.VISIBLE);
                overlayUtils.addPreOrderMarker(new LatLng(0, 0));
            }
        }
    }

    private void getPreOrderDetail() {
        JSONObject bodyJson = new JSONObject();
        try {
            bodyJson = new JSONObject(new Gson().toJson(((MyApplication) getApplication()).getRequestFieldMap()));
            bodyJson.put("orderId", preOrderId);
        } catch (JSONException e) {
            e.printStackTrace();
        }

        RequestBody body = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), bodyJson.toString());
        ApiStore.getInstance().getApiService(UrlContainer.Request.BASE_GATE_URL).preOrderDetail(body).enqueue(new Callback<PreOrderDetailBean>() {
            @Override
            public void onResponse(Call<PreOrderDetailBean> call, Response<PreOrderDetailBean> response) {
                if (response.isSuccessful() && response.body() != null) {
                    if (response.body().getStatus() == 200) {
                        if (response.body().getAttachment().getPreStatus() == 0) {
                            deliverCarBrandModelOrOrderDetail.setText("订单信息");
                            deliverOrderLevel.setText(response.body().getAttachment().getPreCarGrade());
                            deliverOrderLoc.setText(response.body().getAttachment().getPreGetCarAddress());
                            deliverOrderTime.setText(response.body().getAttachment().getPreGetCarTime());
                            deliverOrderDays.setText(response.body().getAttachment().getDayNum());
                        } else if (response.body().getAttachment().getPreStatus() == 1) {
                            deliverCarBrandModelOrOrderDetail.setTextSize(DensityUtils.dp2px(mContext, 12));
                            deliverCarBrandModelOrOrderDetail.setText(response.body().getAttachment().getCarInfo().getModelCN());
                            deliverCarLicense.setText(response.body().getAttachment().getCarInfo().getLicenseTag());
                            ImageLoader.getInstance().displayImage(mContext, ((MyApplication) getApplication()).getImageUrl() + response.body().getAttachment().getCarIcon(), deliverCarIv);
                            deliverCarIv.setVisibility(View.VISIBLE);
                            deliverCarLicense.setVisibility(View.VISIBLE);
                        } else if (response.body().getAttachment().getPreStatus() == 2) {
                            Intent intent = new Intent(mContext, DrivingActivity.class);
                            intent.putExtra(IntentKey.INTENT_ORDER_ID, response.body().getAttachment().getOrderId());
                            intent.putExtra(IntentKey.INTENT_CAR_ID, "");
                            AppManager.getAppManager().finishActivity();
                        }
                    }
                }
            }

            @Override
            public void onFailure(Call<PreOrderDetailBean> call, Throwable t) {

            }
        });
    }

    private void judgeOrder(LatLng centerLocation, int judgeType) {
        if (centerLocation == null) {
            return;
        }
        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject = new JSONObject(new Gson().toJson(((MyApplication) getApplication()).getRequestFieldMap()));
            jsonObject.put("lat", centerLocation.latitude);
            jsonObject.put("lng", centerLocation.longitude);
            jsonObject.put("rent_type", 2);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        RequestBody body = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), jsonObject.toString());
        ApiStore.getInstance().getApiService(UrlContainer.Request.BASE_GATE_URL).judgeOrder("multi-city/v1/cities/" + ((MyApplication) getApplication()).getAreaCode() + "/vehicle/location-order", body).enqueue(new Callback<JudgeOrderBean>() {
            @Override
            public void onResponse(Call<JudgeOrderBean> call, Response<JudgeOrderBean> response) {
                if (response.isSuccessful() && response.body() != null && response.body().getMsg_code() == 200) {
                    if (response.body().getAttachment().getCan_order()) {
                        //可以下单
                        canOrderTip.setText("送车到这里");
                    } else {
                        canOrderTip.setText("超出送车范围");
                    }
                }
            }

            @Override
            public void onFailure(Call<JudgeOrderBean> call, Throwable t) {
            }
        });

    }

    //定位结果监听
    private BDAbstractLocationListener mListener = new BDAbstractLocationListener() {
        @Override
        public void onReceiveLocation(BDLocation bdLocation) {
            if (null != bdLocation && (bdLocation.getLocType() == BDLocation.TypeGpsLocation || bdLocation.getLocType() == BDLocation.TypeNetWorkLocation)) {
                Logger.d("locationDr", "ok");
                bdLocation = LocationFilter.Algorithm(bdLocation);//根据历史定位，对定位的结果平滑过滤
                if (!BuildConfig.DEBUG) {
                    curPosition = new LatLng(bdLocation.getLatitude(), bdLocation.getLongitude());// 更新定位
                    ((MyApplication) getApplication()).setAreaCode(bdLocation.getCityCode());
                    ((MyApplication) getApplication()).setAdCode(bdLocation.getAdCode());
                    DecimalFormat df = new DecimalFormat("#.0000000");
                    ((MyApplication) getApplication()).setCurPosition(df.format(curPosition.latitude), df.format(curPosition.longitude));
                    SPUtils.getInstance(mContext).putStringValue(SPKey.CITY, bdLocation.getCity());
                } else {
                    switch (SPUtils.getInstance(mContext).getIntValue("$s_locationMode")) {
                        case 0:
                        case 1:
                            curPosition = new LatLng(bdLocation.getLatitude(), bdLocation.getLongitude());// 更新定位
                            ((MyApplication) getApplication()).setAreaCode(bdLocation.getCityCode());
                            ((MyApplication) getApplication()).setAdCode(bdLocation.getAdCode());
                            DecimalFormat df = new DecimalFormat("#.0000000");
                            ((MyApplication) getApplication()).setCurPosition(df.format(curPosition.latitude), df.format(curPosition.longitude));
                            SPUtils.getInstance(mContext).putStringValue(SPKey.CITY, bdLocation.getCity());
                            break;
                        case 2:
                            curPosition = new LatLng(Double.parseDouble(SPUtils.getInstance(mContext).getStringValue("$s_fixLatitude")),
                                    Double.parseDouble(SPUtils.getInstance(mContext).getStringValue("$s_fixLongitude")));// 更新定位
                            ((MyApplication) getApplication()).setAreaCode(SPUtils.getInstance(mContext).getStringValue(SPKey.AREA_CODE));
                            ((MyApplication) getApplication()).setAdCode(SPUtils.getInstance(mContext).getStringValue(SPKey.AD_CODE));
                            ((MyApplication) getApplication()).setCurPosition(SPUtils.getInstance(mContext).getStringValue("$s_fixLatitude"),
                                    SPUtils.getInstance(mContext).getStringValue("$s_fixLongitude"));
                            break;
                    }
                }
                mBaiduMap.setMyLocationData(new MyLocationData.Builder().latitude(curPosition.latitude).longitude(curPosition.longitude).build());
                if (isFirstLocation) {//首次成功的定位
                    isFirstLocation = false;
                    mapStatusUtils.animateMove(curPosition, 17, 300);
                    Logger.i("deliver", "location_first");
                }
                Logger.i("deliver", "location_success");
            } else {
                Logger.d("deliver", "errror");
            }
        }
    };

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
                                           @NonNull int[] grantResults) {
        //确保是我们的请求
        if (requestCode == Constants.READ_LOCATION_PERMISSION_REQUEST) {
            if (grantResults.length == 1 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                startLocation();
            } else if (grantResults.length == 1 && grantResults[0] != PackageManager.PERMISSION_GRANTED) {
                final DialogTwoButton inCarDialog = new DialogTwoButton(DeliverCarMapActivity.this);
                inCarDialog.setMessage("您已拒绝定位权限");
                inCarDialog.setYesOnclickListener("确定", new DialogTwoButton.onYesOnclickListener() {
                    @Override
                    public void onYesClick() {
                        inCarDialog.dismiss();
                        startLocation();
                    }
                });
                inCarDialog.setNoOnclickListener("取消", new DialogTwoButton.onNoOnclickListener() {
                    @Override
                    public void onNoClick() {
                        dismissLoadingDialog();
                        inCarDialog.dismiss();
                    }
                });
                inCarDialog.setCancelable(false);
                inCarDialog.show();

            } else {
                super.onRequestPermissionsResult(requestCode, permissions, grantResults);
            }
        }
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
    }

    @Override
    protected void onResume() {
        //为系统的方向传感器注册监听器
        mSensorManager.registerListener(this, mSensorManager.getDefaultSensor(Sensor.TYPE_ORIENTATION),
                SensorManager.SENSOR_DELAY_UI);
        deliverMapView.onResume();
        startLocation();
        super.onResume();
    }

    @Override
    protected void onStop() {
        //取消注册传感器监听
        mSensorManager.unregisterListener(this);
        deliverMapView.onPause();
        super.onStop();
    }

    private void startLocation() {
        if (Build.VERSION.SDK_INT >= 23) {
            if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_COARSE_LOCATION}, Constants.READ_LOCATION_PERMISSION_REQUEST);
            } else {
                mLocClient.restart();
            }
        } else {
            mLocClient.restart();
        }

    }

    @Override
    public void onGetPoiResult(PoiResult result) {
        Logger.i("deliver", "poi_serach_end");
        if (result != null && result.error == SearchResult.ERRORNO.NO_ERROR) {
            List<PoiInfo> poiInfos = result.getAllPoi();
            List<PoiInfoBean> poiInfoBeans = new ArrayList<>();
            if (poiInfos != null && poiInfos.size() > 0) {
                for (int i = 0; i < poiInfos.size(); i++) {
                    PoiInfoBean poiInfoBean = new PoiInfoBean();
                    if (i == 0) {
                        poiInfoBean.setChecked(true);
                    }
                    poiInfoBean.setName(poiInfos.get(i).name);
                    poiInfoBean.setAddress(poiInfos.get(i).address);
                    poiInfoBean.setLatLng(poiInfos.get(i).location);
                    poiInfoBeans.add(poiInfoBean);
                }
                //初始化及监听rv
                LinearLayoutManager manager = new LinearLayoutManager(this);
                manager.setOrientation(LinearLayoutManager.VERTICAL);
                deliverBottomRv.setLayoutManager(manager);
                rcAdapter = new DeliverLocAdapter(poiInfoBeans);
                deliverBottomRv.setAdapter(rcAdapter);
                rcAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
                    @Override
                    public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                        for (int i = 0; i < poiInfoBeans.size(); i++) {
                            poiInfoBeans.get(i).setChecked(false);
                        }
                        poiInfoBeans.get(position).setChecked(true);
                        useCarAddress = poiInfoBeans.get(position).getName();
                        useCarLoc = poiInfoBeans.get(position).getLatLng();
                        mapStatusUtils.animateMove(poiInfoBeans.get(position).getLatLng(), -1, 300);
                        rcAdapter.notifyDataSetChanged();

                    }
                });
                //初始化第一个
                useCarAddress = poiInfoBeans.get(0).getName();
                useCarLoc = poiInfoBeans.get(0).getLatLng();
                mapStatusUtils.animateMove(poiInfoBeans.get(0).getLatLng(), -1, 300);
                canPoiSearch = false;
                judgeOrder(useCarLoc, 0);
            } else {
                SystemToastUtils.makeText(mContext, "停车场查询失败，请重试", ToastUtils.LENGTH_SHORT).show();
            }
        } else {
            SystemToastUtils.makeText(mContext, "停车场查询失败，请重试", ToastUtils.LENGTH_SHORT).show();
        }
    }

    @Override
    public void onGetPoiDetailResult(PoiDetailResult poiDetailResult) {

    }

    @Override
    public void onGetPoiIndoorResult(PoiIndoorResult poiIndoorResult) {

    }

    @Override
    public void onSensorChanged(SensorEvent sensorEvent) {
        double x = sensorEvent.values[SensorManager.DATA_X];
        if (Math.abs(x - lastX) > 1.0) {
            int mCurrentDirection = (int) x;
            if (curPosition != null) {
                locData = new MyLocationData.Builder()
                        // .accuracy(mCurrentAccuracy)
                        // 此处设置开发者获取到的方向信息，顺时针0-360
                        .direction(mCurrentDirection).latitude(curPosition.latitude)
                        .longitude(curPosition.longitude).build();
                mBaiduMap.setMyLocationData(locData);
            }
        }
        lastX = x;
    }

    @Override
    public void onAccuracyChanged(Sensor sensor, int accuracy) {

    }

    @OnClick({R.id.deliver_cancel_order, R.id.title_back, R.id.imageView_locate, R.id.deliver_loc_search, R.id.deliver_loc_search_et, R.id.deliver_loc_confirm})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.title_back:
                AppManager.getAppManager().finishActivity();
                break;
            case R.id.imageView_locate:
                canPoiSearch = true;
                if (curPosition != null) {
                    mapStatusUtils.animateMove(curPosition, 17, 600);
                }
                break;
            case R.id.deliver_loc_search:
            case R.id.deliver_loc_search_et:
                Intent intent = new Intent(mContext, SearchParkActivity.class);
                intent.putExtra("intentFrom", 1);
                intent.putExtra("content", "");
                startActivity(intent);
                break;
            case R.id.deliver_loc_confirm:
                Intent intent1 = new Intent(mContext, DeliverCarActivity.class);
                intent1.putExtra("lat", useCarLoc.latitude);
                intent1.putExtra("lng", useCarLoc.longitude);
                intent1.putExtra("searchParkName", useCarAddress);
                startActivity(intent1);
                break;
            case R.id.deliver_cancel_order:
                cancelOrder();
                break;
        }
    }

    private void cancelOrder() {
    }

    @Override
    protected void onDestroy() {
        if (mLocClient != null) {
            mLocClient.stop();
            mLocClient.unRegisterLocationListener(mListener);
            mLocClient = null;
        }
        super.onDestroy();
    }
}
